﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using ServerLib.Core;

namespace ServerLib.Data
{
    public class DataRowRecord
    {
        #region Private Properties
        
        /// <summary>Contains the new status of the DataRow</summary>
        private bool dataRowIsNew = false;

        /// <summary>Contains a reference to a database connection object</summary>
        private IDatabase dataConnection;

        /// <summary>Contains the DataRow object that holds field data about the Domain record</summary>
        private DataRow dataRowContainer;
        #endregion

        #region Public Properties

        /// <summary>
        /// Gets or sets the DataRow object that contains the domain data record
        /// </summary>
        virtual public DataRow InternalDataRow
        {
            get
            {
                return this.dataRowContainer;
            }

            set
            {
                this.dataRowContainer = value;
            }
        }

        /// <summary>
        /// Gets the internal database connection object
        /// </summary>
        virtual public IDatabase Connection
        {
            get
            {
                return this.dataConnection;
            }
        }

        #endregion

        #region Public Constructors

        /// <summary>
        /// Initializes the Record object with a new DataRow class
        /// </summary>
        /// <param name="dataConnection">The IDatabase object to connect with</param>
        public DataRowRecord(IDatabase dataConnection) : this(dataConnection, string.Empty, string.Empty, -999)
        {
        }

        /// <summary>
        /// Initializes the Record object with a new DataRow class
        /// </summary>
        /// <param name="dataConnection">The IDatabase object to connect with</param>
        /// <param name="tableName">The Record table name to load into the Record object</param>
        /// <param name="fieldName">The Record table field name name used to identify when loading the recordId</param>
        /// <param name="recordId">The unique record ID number to load into the Record object</param>
        public DataRowRecord(IDatabase dataConnection, string tableName, string fieldName, int recordId)
        {
            if (dataConnection != null)
            {
                this.dataConnection = dataConnection;

                bool wasConnected = dataConnection.IsConnected;

                if (!wasConnected)
                {
                    dataConnection.Open();
                }

                if (dataConnection.IsConnected)
                {
                    DataTable eventsTable = null;

                    if ((tableName != null && fieldName != null) ? (tableName.Length > 0 && fieldName.Length > 0) : false)
                    {
                        // get a data table
                        eventsTable = dataConnection.SelectQuery(SqlCommandStringBuilder.BuildSelect(tableName, null, string.Format("{0}={1}", fieldName, recordId), string.Empty));
                    }

                    if (eventsTable != null)
                    {
                        if (eventsTable.Rows.Count > 0)
                        {
                            this.dataRowContainer = eventsTable.Rows[0];
                        }
                        else
                        {
                            dataRowIsNew = true;
                            this.dataRowContainer = eventsTable.NewRow();
                        }
                    }
                }

                if (!wasConnected)
                {
                    dataConnection.Close();
                }
            }
        }

        /// <summary>
        /// Initializes the Record object with a new DataRow class
        /// </summary>
        /// <param name="dataTable">The DataTable object to retrieve a new DataRow object from</param>
        public DataRowRecord(DataTable dataTable)
        {
            dataRowIsNew = true;
            this.dataRowContainer = dataTable.NewRow();
        }

        /// <summary>
        /// Initializes the Record object with a new DataRow class
        /// </summary>
        /// <param name="dataRow">The DataRow object to initialize the Record object with</param>
        public DataRowRecord(DataRow dataRow)
        {
            this.dataRowContainer = dataRow;
        }
        #endregion

        #region Public Methods

        /// <summary>
        /// Saves the DataRow record and returns a unique identifier value
        /// </summary>
        /// <returns>Returns the unique identifier value of the new row</returns>
        virtual public int Save()
        {
            int resultValue = 0;

            try
            {
                if (dataConnection != null)
                {
                    bool wasConnected = this.dataConnection.IsConnected;

                    if (!wasConnected)
                    {
                        this.dataConnection.Open();
                    }

                    if (this.dataConnection.IsConnected)
                    {
                        if (dataRowContainer.Table != null)
                        {
                            if (dataRowIsNew)
                            {
                                dataRowContainer.Table.Rows.Add(dataRowContainer);
                                dataRowContainer.Table.AcceptChanges();
                                resultValue = dataConnection.GetCurrentIdentity(dataRowContainer.Table.TableName);
                            }
                        }
                        else
                        {
                            dataRowContainer.AcceptChanges();
                        }
                    }

                    if (!wasConnected)
                    {
                        this.dataConnection.Close();
                    }
                }
            }
            catch(Exception ex)
            {
                resultValue = -1;
            }
            return resultValue;
        }

        /// <summary>
        /// Deleted the DataRow record
        /// </summary>
        /// <returns>Returns true on success</returns>
        virtual public bool Delete()
        {
            bool resultValue = true;

            try
            {
                if (dataConnection != null)
                {
                    bool wasConnected = this.dataConnection.IsConnected;

                    if (!wasConnected)
                    {
                        this.dataConnection.Open();
                    }

                    if (this.dataConnection.IsConnected)
                    {
                        dataRowContainer.Delete();
                    }

                    if (!wasConnected)
                    {
                        this.dataConnection.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                resultValue = false;
            }

            return resultValue;
        }

        #endregion
    }
}
